package com.foogui.primary.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class LockTicket implements Ticket {
    private int count = 20;

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void removeTicket() throws InterruptedException {
        lock.lock();
        try {
            //这里必须使用while判断，否则可能出现虚假唤醒的问题
            while (count <= 0) condition.await();
            System.out.println(Thread.currentThread().getName() + "卖了一张票，还剩" + (--count) + "张");
            Thread.sleep(100);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

    public void addTicket() throws InterruptedException {

        lock.lock();
        try {
            //这里必须使用while判断，否则可能出现虚假唤醒的问题
            while (count != 0) condition.await();
            count = 20;
            System.out.println("重新补充票数，总票数为" + count + "张");
            Thread.sleep(100);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }
}
